// pages/messageChat/messageChat.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isScrolling:false,
    isNewsMsg: false,
    ifReadHistory: false,
    chatHeight:0,
    triggered: false,
    userId: 1,
    toView: "",
    backIcon:"/chatIcon/Back_Icon.png",
    emotionIcon:"/chatIcon/Emoticon_Icon.png",
    cameraIcon:"/chatIcon/Camera_Icon.png",
    sendIcon:"/chatIcon/SendMessage.png",
    cusHeadIcon:"/chatIcon/head.png",
    endBoxHeight:180,
    messageBoxHeight:110,
    messageCome:"/chatIcon/messageCome.png",
    messageOut:"/chatIcon/messageOut.png",
    myMessage: "",
    outMessage: "",
    myintervalid: "",
    page:1,
    talker:{
      ID:2,
      name: "",
      school:"",
      gender:"",
      img:"/chatIcon/profile.png",
      state:"rgb(67, 240, 84)"   //表示对方状态，rgb(67, 240, 84)表示在线时颜色
    },
    msgList: [
    ]
  },

  updateHeight(e){
    let str = "";
    if (this.data.myMessage) {
      str = this.data.myMessage + "\n"
    }else{
      str = this.data.myMessage
    }
    this.setData({
      endBoxHeight: 180 + (38 * e.detail.lineCount),
      messageBoxHeight: 110 + (38 * e.detail.lineCount),
      outMessage: str
    });
    console.log(this.data.endBoxHeight);
    console.log(this.data.messageBoxHeight);
  },

  sendMessage(e){
    var time = new Date();
    let str = time.getFullYear()+"-"+(time.getMonth()+1)+"-"+time.getDate()+" "+(time.getHours()-8)+":"+time.getMinutes()+":"+time.getSeconds();
    let that = this;
    var header={};
    header = { 
      'content-type': 'application/json'
    };
    var cookie = wx.getStorageSync("cookieKey");
    header['cookie'] = cookie;
    wx.request({
      url: 'http://localhost:8080/message',
      header:header,
      method: 'POST',
      data:{
        "senderId": that.data.userId,
        "receiverId": that.data.talker.ID,
        "content": that.data.myMessage,
        "time": str
      },
      success(res) {
        console.log("sendRes:",res);
        that.setData({
          "myMessage": '',
          "ifReadHistory": false,
          "page": 1,
        });
        that.setData({
          "toView": that.data.msgList[that.data.msgList.length-1].ID,
        })
      }
    })
  },

  refresh(){
    var header={};
    header = { 
      'content-type': 'application/x-www-form-urlencoded'
    };
    var cookie = wx.getStorageSync("cookieKey");
    header['cookie'] = cookie;
    let that = this;
    that.data.myintervalid = setInterval(function () {
      if (!that.data.ifReadHistory){
        console.log("refresh")
        let newList = [];
        wx.request({
          url: 'http://localhost:8080/message/'+ that.data.talker.ID +'/1',
          header:header,
          method: "GET",
          success(res){
           console.log("res:",res)
            let list = res.data.data.reverse();
            for(let i = 0; i < res.data.data.length; i++){
              let msg = {
                ID: list[i].id,
                speaker: (list[i].senderId==that.data.userId?'customer':'server'),
                contentType: 'text',
                content: list[i].content
              }
              newList.push(msg)
            }
            if(res.data.data.length != 0){
              if(that.data.msgList.length == 0){
                that.setData({
                  "msgList": newList
                })
              }else{
                if(res.data.data[res.data.data.length-1].id != that.data.msgList[that.data.msgList.length-1].ID){
                  that.setData({
                    "msgList": newList
                  })
                }
              }
            }
          }
        })
      }else{
        wx.request({
          url: 'http://localhost:8080/message/'+ that.data.talker.ID +'/1',
          method: "GET",
          header:header,
          success(res){
            console.log(res.data)
            if ((res.data.data[0].id != that.data.msgList[that.data.msgList.length - 1].ID)&&(res.data.data[0].senderId == that.data.talker.ID)) {
              let msgList = that.data.msgList;
              let msg = {
                ID: res.data.data[0].id,
                speaker: (res.data.data[0].senderId==that.data.userId?'customer':'server'),
                contentType: 'text',
                content: res.data.data[0].content
              }
              msgList.push(msg);
              that.setData({
                "isNewsMsg": true,
                "msgList": msgList
              })
              
            }else{
              console.log("nofresh")
            }
          }
        })
      }
    }, 1000)
    },

  refreshHistory(){
    var header={};
    header = { 
      'content-type': 'application/x-www-form-urlencoded'
    };
    var cookie = wx.getStorageSync("cookieKey");
    header['cookie'] = cookie;
    if (this.data.isScrolling) {
      return
    }
    this.setData({
      "isScrolling": true
    })
    console.log("startPage:",this.data.page)
    this.setData({
      "ifReadHistory": true
    })
    let that = this;    
    let msgList = this.data.msgList;
    wx.request({
      url: 'http://localhost:8080/message/'+ that.data.talker.ID +'/'+(this.data.page+1),
      header: header,
      method: "GET",
      success(res){
        console.log("pull:",res.data.data)
        console.log("page:",that.data.page)
        let list = res.data.data;
        for(let i = 0; i < res.data.data.length; i++){
          let msg = {
            ID: list[i].id,
            speaker: (list[i].senderId==that.data.userId?'customer':'server'),
            contentType: 'text',
            content: list[i].content
          }
          msgList.unshift(msg)
        }
        that.setData({
          "msgList": msgList,
          "triggered": false,
          "page": res.data.data.length==0?that.data.page:that.data.page+1,
          "isScrolling": false
        })
      }
    })
  },

  jump(){
    this.setData({
      "ifReadHistory": false,
      "toView": this.data.msgList[this.data.msgList.length-1].ID,
      "isNewsMsg": false,
      "page": 1,
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    let talkerId = options.talkerId;
    this.setData({
      "talker.ID": talkerId 
    })
    var header={};
    header = { 
      'content-type': 'application/x-www-form-urlencoded'
    };
    var cookie = wx.getStorageSync("cookieKey");
    header['cookie'] = cookie;
    //获取userID
    wx.request({
      url: 'http://localhost:8080/user/userId',
      header:header,
      success(res){
        that.setData({
          "userId": res.data.data
        })
        console.log("userId:",that.data.userId)
      }
    })
    //获取talker信息
    let name = "talker.name"
    let school = "talker.school"
    let gender = "talker.gender"
    wx.request({
      url: 'http://localhost:8080/user/userInfo/'+that.data.talker.ID,
      header: header,
      success(res){
        console.log("info:",res.data)
        let talker = {
          ID: that.data.talker.ID,
          name: res.data.data.name,
          school: res.data.data.school,
          gender: res.data.data.gender,
          img:"/chatIcon/profile.png",
          state:"rgb(67, 240, 84)"   //表示对方状态，rgb(67, 240, 84)表示在线时颜色
        }
        that.setData({
          "talker": talker
        })
        console.log("result:",that.data.talker)
      }
    })
     //高度自适应
      wx.getSystemInfo({
          success: function (res) {
              var clientHeight = res.windowHeight,
               clientWidth = res.windowWidth,
               rpxR = 750 / clientWidth;
              var chatH = clientHeight * rpxR;
              that.setData({
                  chatHeight: chatH - 179.32
              });
          }
      });
      wx.setNavigationBarTitle({
        title: '互助珞珈',
      })
      // 初始化消息
      let msgList = []
      wx.request({
        url: 'http://localhost:8080/message/'+ that.data.talker.ID +'/'+this.data.page,
        method: "GET",
        header: header,
        success(res){
          console.log(res.data.data)
          console.log("")
          let list = res.data.data.reverse();
          for(let i = 0; i < res.data.data.length; i++){
            let msg = {
              ID: list[i].id,
              speaker: (list[i].senderId==that.data.userId?'customer':'server'),
              contentType: 'text',
              content: list[i].content
            }
            msgList.push(msg)
          }
          that.setData({
            "msgList": msgList
          })
        }
      })
      
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.refresh()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})